var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var isRefresh = false;
var _limitMenu = system.MENULIMIT.MONEY10;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'money/expense/page';

var Utils = {
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择店铺',
			content : 'url:'+config.BASEPATH+'base/shop/list_dialog_bymodule',
			data : {multiselect:false,module:'expense'},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#ep_shop_code").val(selected.sp_code);
				$("#shop_name").val(selected.sp_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#ep_shop_code").val(selected.sp_code);
					$("#shop_name").val(selected.sp_name);
				}
			},
			cancel:true
		});
	},
	doQueryBank : function(){
		commonDia = $.dialog({
			title : '选择银行账户',
			content : 'url:'+config.BASEPATH+'money/bank/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#ep_ba_code").val(selected.ba_code);
				$("#ba_name").val(selected.ba_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#ep_ba_code").val(selected.ba_code);
					$("#ba_name").val(selected.ba_name);
				}
			},
			cancel:true
		});
	},
	doQueryEmp : function(){
		commonDia = $.dialog({
			title : '选择经办人',
			content : 'url:'+config.BASEPATH+'base/emp/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#ep_manager").val(selected.em_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#ep_manager").val(selected.em_name);
				}
			},
			cancel:true
		});
	}
};

var handle = {
	operate: function(oper, id){//修改、新增
		if(oper == 'add'){
			url = config.BASEPATH+"money/expense/to_add";
			data = {oper: oper, callback:this.callback};
		}else if(oper == 'edit'){
			url = config.BASEPATH+"money/expense/to_update?ep_id="+id;
			data = {oper: oper,callback: this.callback};
		}else if(oper == 'view'){
			url = config.BASEPATH+"money/expense/to_view?ep_id="+id;
			data = {oper: oper,callback: this.callback};
		}else if(oper == 'approve'){
			url = config.BASEPATH+"money/expense/to_view?ep_id="+id;
			data = {oper: oper,callback: this.callback};
		}else{
			return false;
		}
		$.dialog({
			title : false,
			content : 'url:'+url,
			data: data,
			max : false,
			min : false,
			cache : false,
			lock: false
		}).max();
	},
	del: function(ids){//删除
		var numbers = '';
        for(var i=0;i<ids.length;i++){
        	var rowData = $('#grid').jqGrid('getRowData', ids[i]);
        	
        	if(rowData.ep_ar_state == "已审核"){
				Public.tips({type: 1, content : "单据已审核，不能删除"});
				return;
			}
//        	if (rowData.FE_US_Id != SYSTEM.US_ID) {
//                $.dialog.tips("只能删除本人的数据", "2", "32X32/fail.png");
//                return;
//            }
        	numbers += rowData.ep_number+',';
        }
        if(numbers != ''){
        	numbers = numbers.substring(0, numbers.length-1);
        }
	 	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
			$.ajax({
				type:"POST",
				url:config.BASEPATH+'money/expense/del',
				data:{"numbers":numbers},
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						Public.tips({type: 3, content : '删除成功!'});
						for(var i=0;i<ids.length;i++){
							$('#grid').jqGrid('delRowData', ids[i]);
						}
					}else{
						Public.tips({type: 1, content : data.message});
					}
				}
			});
		});	
    },
    approve:function(ids){
    	var numbers = '';
    	var totalMoney = 0;
        for(var i=0;i<ids.length;i++){
        	var rowData = $('#grid').jqGrid('getRowData', ids[i]);
        	if(rowData.ep_ar_state != "未审核"){
				Public.tips({type: 1, content : "单据已审核，不能重复审核"});
				return;
			}
        	numbers += rowData.ep_number+',';
        	totalMoney += parseFloat(rowData.ep_money);
        }
        if(numbers != ''){
        	numbers = numbers.substring(0, numbers.length-1);
        }
        var tip = '本次批量审核'+ids.length+'笔单据，支出金额合计：'+totalMoney.toFixed(2)+'元。';
        commonDia = $.dialog({ 
		   	id:'approve_confirm',
		   	title:'审批页面',
		   	data:{tip:tip},
		   	max: false,
		   	min: false,
		   	lock:true,
		   	width:300,
		   	height:250,
		   	drag: true,
		   	resize:false,
		   	content:'url:'+config.BASEPATH+'approve/to_confirm_batch',
		   	fixed:false,
		   	close : function(){
		   		var ar_infos = commonDia.content.ar_infos;
		   		if(ar_infos != undefined){
		   			handle.doApprove(ar_infos,numbers);
		   		}
		   	}
	    });
    },
    doApprove:function(ar_infos,numbers){
		$("#btn-approve").attr("disabled",true);
		var params = "";
		params += "numbers="+numbers;
		params += "&ar_state="+ar_infos.ar_state;
		params += "&ar_describe="+Public.encodeURI(ar_infos.ar_describe);
		$.ajax({
            type: "POST",
            url: config.BASEPATH+"money/expense/approveBatch",
            data: params,
            cache:false,
			dataType:"json",
            success: function (data) {
            	if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : '审核成功'});
					THISPAGE.reloadData();
				}else{
					Public.tips({type: 1, content : data.message});
				}
				$("#btn-approve").attr("disabled",false);
            }
        });
	},
    callback: function(data, oper, dialogWin){
		if(oper == "edit") {
			THISPAGE.reloadData();
			dialogWin && dialogWin.api.close();
		}
		if(oper == "approve") {
			$("#grid").jqGrid('setRowData', data.id, data);
			dialogWin && dialogWin.api.close();
		}
		if(oper == "view") {
			$("#grid").jqGrid('setRowData', data.id, data);
			dialogWin && dialogWin.api.close();
		}
		if(oper == "add"){
			THISPAGE.reloadData();
			dialogWin && dialogWin.api.close();
		}
	},
	operFmatter : function(val, opt, row){
		var btnHtml = '';
		if (row.ep_ar_state == '0') {
            btnHtml += '<input type="button" value="审核" class="btn_sp" onclick="javascript:handle.operate(\'approve\',' + opt.rowId + ');" />';
        }else if (row.ep_ar_state == '2') {
            btnHtml += '<input type="button" value="修改" class="btn_xg" onclick="javascript:handle.operate(\'edit\',' + opt.rowId + ');" />';
        }else if (row.ep_ar_state == '1') {//审核通过
        	btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
        } 
		btnHtml += '<input type="button" value="流程" class="btn_qh" onclick="javascript:listBillProcess(\''+row.ep_number+'\',\'t_money_expense\');" />';
		return btnHtml;
	},
	formatArState:function(val, opt, row){//0：未审核；1：已审核2：已退回
		if(val == 0){
			return '未审核';
		}else if(val == 1){
			return '已审核';
		}else if(val == 2){
			return '已退回';
		}
		return val;
	}
};
var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();	
	},
	initDom:function(){
		this.$_date = $("#date").cssRadio({ callback: function($_obj){
			dateRedioClick($_obj.find("input").attr("id"));
		}});
		dateRedioClick("theDate");
		this.$_ar_state = $("#ar_state").cssRadio({ callback: function($_obj){
			$("#ep_ar_state").val($_obj.find("input").val());
		}});
		Public.buildTimeTypeCombo("span_timetype", "time_type");
	},
	initGrid:function(){
		var gridWH = Public.setGrid();
		var colModel = [
	    	{name: 'operate',label:'操作',width: 100, formatter: handle.operFmatter,align:'center', sortable:false},
	    	{name: 'ep_number',label:'单据编号',index: 'ep_number',width:150},
	    	{name: 'shop_name',label:'店铺名称',index: 'shop_name',width:110},
	    	{name: 'ba_name',label:'银行帐户',index: 'ba_name',width:75},
	    	{name: 'ep_manager',label:'经办人',index: 'ep_manager',width:100},
	    	{name: 'dm_name',label:'部门',index: 'ep_dm_code',width:100},
	    	{name: 'ep_date',label:'日期',index: 'ep_date',width:80},
	    	{name: 'ep_money',label:'金额',index: 'ep_money',width:80,align:'right',formatter: PriceLimit.formatMoney},
	    	{name: 'ep_ar_state',label:'状态',index: 'ep_ar_state',width:80,formatter: handle.formatArState},
	    	{name: 'ep_maker',label:'制单人',index: 'ep_maker',width:100}
	    ];
		$('#grid').jqGrid({
            url:queryurl+'?'+THISPAGE.buildParams(),
			datatype: 'json',
			width: gridWH.w-12,
			height: gridWH.h-20,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:true,//多选
			viewrecords: true,
			rowNum:config.BASEROWNUM,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
				repeatitems : false,
				id: 'ep_id'  //图标ID
			},
			loadComplete: function(data){
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	buildParams : function(){
		var params = '';
		params += 'ep_ar_state='+$("#ep_ar_state").val();
		params += '&begindate='+$("#begindate").val();
		params += '&enddate='+$("#enddate").val();
		params += '&ep_shop_code='+$("#ep_shop_code").val();
		params += '&ep_ba_code='+$("#ep_ba_code").val();
		params += '&ep_manager='+Public.encodeURI($("#ep_manager").val());
		params += '&ep_number='+Public.encodeURI($("#ep_number").val());
		return params;
	},
	reset:function(){
		$("#ep_number").val("");
		$("#ep_manager").val("");
		$("#ep_shop_code").val("");
		$("#shop_name").val("");
		$("#ep_ba_code").val("");
		$("#ba_name").val("");
		THISPAGE.$_date.setValue(0);
		THISPAGE.$_ar_state.setValue(0);
		$("#begindate").val("");
		$("#enddate").val("");
	},
	reloadData:function(){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			THISPAGE.reloadData();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		//新增
		$('#btn-add').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.INSERT)) {
				return ;
			}
			handle.operate('add');
		});
		$('#btn-del').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
				return ;
			}
			var ids = $('#grid').jqGrid('getGridParam', 'selarrrow');
            if(ids == null || ids == '' || ids.length == 0){
            	Public.tips({type: 2, content : '你没有选中单据,请重新选择!'});
            	return;            	
            }
            handle.del(ids);
		});
		$('#btn-approve').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
				return ;
			}
			var ids = $('#grid').jqGrid('getGridParam', 'selarrrow');
			if(ids == null || ids == '' || ids.length == 0){
				Public.tips({type: 2, content : '你没有选中单据,请重新选择!'});
				return;            	
			}
			handle.approve(ids);
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
	}
}
THISPAGE.init();